// pages/comments/comments.js
const { getComments, getCommentsCount } = require('../../api/index.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    actived: 0,
    obj: {
      valueId: 0,
      page: 1,
      size: 10
    },
    commentsObj: {
      data: []
    },
    commentsCount: {},
    switched: false,
    toTop: 0
  },
  switchTab(e) { //tab切换
    let id = e.currentTarget.id;
    if(id != this.data.actived) {
      this.setData({
        actived: id,
        'obj.page': 1,
        'obj.showType': id,
        'commentsObj.totalPages': 1,
        switched: true
      })
      this.getComments()
    }
  },
  async getComments() { //全部评论
    if (this.data.commentsObj.totalPages < this.data.obj.page) return;
    const res = await getComments(this.data.obj)
    let str = `commentsObj.data[${this.data.commentsObj.data.length}]`
    if (this.data.switched) {
      this.setData({
        'commentsObj.data': [],
        toTop: 0
      })
    }
    this.setData({
      [str]: res.data,
      'obj.page': ++this.data.obj.page,
      'commentsObj.totalPages': res.totalPages,
      switched: false
    })
  },
  async getCommentsCount() { //评论数
    const commentsCount = await getCommentsCount(this.data.obj.valueId)
    this.setData({
      commentsCount
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'obj.valueId': options.id
    })
    this.getComments()
    this.getCommentsCount()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})